<?php

	Tekuna :: load('org.tekuna.core.persistence.TextDB');
	TekunaApplication :: load('components.model.ArticleModelException');

	class ArticleModel implements TekunaModel {
		
		public
			$id = -1,
			$date = 0,
			$title = '',
			$text = '';
		
		
		private static function getDB() {
			
			return new TextDB('articles', array('date', 'title', 'text'));
		}
		
		
		public function loadArticle($iArticleID) {
			
			// select the article by its ID
			$arrData = self :: getDB() -> selectWhere('id', $iArticleID);
			
			// check the article exists
			if (count($arrData) == 0) {
				
				throw new ArticleModelException('%error.article.does.not.exist%');
			}
			
			$this -> id = (int) $arrData[0]['id'];
			$this -> date = (int) $arrData[0]['date'];
			$this -> title = (string) $arrData[0]['title'];
			$this -> text = (string) $arrData[0]['text'];
		}
		
		
		public function save() {
			
			if ($this -> id == -1) {
				
				// create new article
				$arrInsert = array('date' => $this -> date,
				                   'title' => $this -> title,
				                   'text' => $this -> text);
				
				$this -> id = self :: getDB() -> insert($arrInsert);
			}
			else {
				
				// update existing article
				self :: getDB() -> updateWhere('id', $this -> id, 'date', $this -> date);
				self :: getDB() -> updateWhere('id', $this -> id, 'title', $this -> title);
				self :: getDB() -> updateWhere('id', $this -> id, 'text', $this -> text);
			}
		}
		
		
		public static function findAll() {
			
			$arrArticles = array();
			
			foreach (self :: getDB() -> selectAll() as $arrData) {
				
				$objArticle = new ArticleModel();
				$objArticle -> id = (int) $arrData['id'];
				$objArticle -> date = (int) $arrData['date'];
				$objArticle -> title = (string) $arrData['title'];
				$objArticle -> text = (string) $arrData['text'];
				
				$arrArticles[] = $objArticle;
			}
			
			return $arrArticles;
		}
	}